package com.retailshop.shopuser.WapUserController;

import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;

import com.qiniu.util.Auth;
import com.retailshop.shopuser.common.MessageConstants;
import com.retailshop.shopuser.entity.UploadFileConfig;
import com.retailshop.shopuser.service.UserNoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.UUID;

@CrossOrigin
@RequestMapping("/wap")
@Controller
public class UploadController {

    @Autowired
    UploadFileConfig uploadFileConfig;
    @Autowired
    UserNoService userNoService;

    /**
     * 上传文件的接口
      * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/upload",method = RequestMethod.POST)
    public com.retailshop.shopuser.common.Response upload(HttpServletRequest request) {
        Logger logger =LoggerFactory.getLogger(UploadController.class);
        try {
            MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;

            logger.info("文件上传：");

            /** 页面控件的文件流* */
            MultipartFile multipartFile = multipartRequest.getFile("file");

            /** 获取文件的后缀* */
            String suffix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));

            //判断后缀
            if (!("|.jpg|.png|".contains("|" + suffix.toLowerCase() + "|"))) {
                return new com.retailshop.shopuser.common.Response(MessageConstants.FILE_TYPE, null, 0, "", request);
            }

            //判断文件大小
            long size = multipartFile.getSize();
            if (size > uploadFileConfig.getImgSize()) {

                return new com.retailshop.shopuser.common.Response(MessageConstants.FILE_SIZE, null, 0, "", request);
            }

            /**生成文件名称* */
            String fileName = "apply" + UUID.randomUUID().toString().replaceAll("-", "").substring(10, 15) + suffix;// 构建文件名称

            logger.info("文件名称："+fileName);

            //构造一个带指定Zone对象的配置类
            Configuration cfg = new Configuration(Zone.zone2());

            //...其他参数参考类注释
            UploadManager uploadManager = new UploadManager(cfg);
            //...生成上传凭证，然后准备上传

            //获取流
            byte[] uploadBytes = multipartFile.getBytes();
            //默认不指定key的情况下，以文件内容的hash值作为文件名
            String key = fileName;

            Auth auth = Auth.create(uploadFileConfig.getAccessKey(), uploadFileConfig.getSecretKey());
            String upToken = auth.uploadToken(uploadFileConfig.getBucket());
            Response response = uploadManager.put(uploadBytes, key, upToken);
            String filePath=uploadFileConfig.getDomainName()+"/"+fileName;
            return new  com.retailshop.shopuser.common.Response(MessageConstants.MSG_SUCCESS,filePath,0,"",request);

        } catch (Exception e) {

            e.printStackTrace();
            return new  com.retailshop.shopuser.common.Response(MessageConstants.MSG_SYS_ERROR,null,0,"",request);
        }

    }


    /**
     *保存用户申请店铺的资料
     * @param
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/saveUploadInfo")
   public com.retailshop.shopuser.common.Response saveUploadInfo(HttpServletRequest request){
                try {
                    boolean flag=false;
                  flag =userNoService.applyStore(request);

                  return new com.retailshop.shopuser.common.Response(MessageConstants.MSG_SUCCESS,flag,0,"",request);

                }catch (Exception e){
                    e.printStackTrace();
                    return new com.retailshop.shopuser.common.Response(MessageConstants.MSG_SYS_ERROR,null,0,"",request);
                }

    }

}